#include "irobot_abstract.h"


#ifdef SERIAL
#include <unistd.h>
#include <stdio.h>
#include <time.h>
Serial s;
#endif

void ir_initialize(int verbose) {
	#ifdef CMOD
	initializeCommandModule();
	#endif

	#ifdef SERIAL
	// Open the serial port.
	serialOpen(&s, "/dev/ttyS0", B57600, verbose);

	// Flush any input that might be buffered already.
	unsigned char c;
	while(serialNumBytesWaiting(&s) > 0) serialGetChar(&s,&c);
	//sleep(1);
	//while(serialNumBytesWaiting(&s) > 0) serialGetChar(&s,&c);
	#endif
}

void ir_finish() {
	#ifdef SERIAL
	serialClose(&s);
	#endif
}

void ir_send_byte(unsigned char c) {
	#ifdef CMOD
	sendByte((uint8_t) c);
	#endif
	#ifdef SERIAL
	while(!serialSend(&s,c));
	#endif
}
	
unsigned char ir_get_byte(void) {
	#ifdef CMOD
	return (unsigned char)getByte();
	#endif
	#ifdef SERIAL
	unsigned char c;
	//ir_sleep(100);
	//serialGetChar(&s,&c);
	while(!serialGetChar(&s,&c));
	return c;
	#endif
}

void ir_sleep(unsigned int milliseconds) {
	#ifdef CMOD
	delay((uint16_t)milliseconds);
	#endif
	#ifdef SERIAL
	sleep(milliseconds/1000);
	usleep((milliseconds%1000)*1000);
	#endif
}

unsigned int ir_time() {
	#ifdef CMOD
	return cmod_time()/1000;
	#endif
	#ifdef SERIAL
	return time();
	#endif
}
